package com.ai.aichat.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.ResponseExtractor;
import org.springframework.web.client.RestTemplate;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

/**
 * @author lwlianghehe@gmail.com
 * @date 2025/9/11
 */
@Service
@Slf4j
public class OpenAIService {

    private ObjectMapper objectMapper = new ObjectMapper();
    @Qualifier("openAiHttpClient")
    @Autowired
    private RestTemplate restTemplate;

    public Map sendText(String model, String message) throws JsonProcessingException {
        String url = "https://api.openai.com/v1/responses";
        Map<String, String> map = new HashMap<>();
        map.put("model", model);
        map.put("input", message);


        HttpEntity<Map> httpEntity = new HttpEntity<>(map, null); // 这里传body 没有传header

        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        return objectMapper.readValue(exchange.getBody(), Map.class);
    }

    public void sendText(String model, String message, Boolean stream,
                         Consumer<String> onDelta) {
        String url = "https://api.openai.com/v1/responses";

        Map<String, Object> map = new HashMap<>();
        map.put("model", model);
        map.put("input", message);
        map.put("stream", stream);

        RequestCallback requestCallback = request -> {
            request.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            request.getBody().write(objectMapper.writeValueAsBytes(map));
        };

        // 逐行读取响应：仅处理以 "data:" 开头的 SSE 数据行
        ResponseExtractor<Void> responseExtractor = response -> {
            try (InputStream in = response.getBody();
                 BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    log.info("chatStream,{}", line); // 调试：观察服务端推送的原始行
                    if (!line.startsWith("data:")) {
                        continue; // 忽略注释或空行
                    }
                    String data = line.substring("data:".length()).trim(); // 截取 json 字符串
                    if ("[DONE]".equals(data)) { // 约定的结束标记
                        break;
                    }
                    try {
                        // OpenAI Responses 的分片一般是 JSON，包含 type 与负载
                        Map<String, Object> dataMap = objectMapper.readValue(data, Map.class);
                        Object type = dataMap.get("type");
                        // 仅透传文本增量事件，其它事件（如 response.completed）可按需处理
                        if (type != null && "response.output_text.delta".equals(type.toString())) {
                            String delta = String.valueOf(dataMap.getOrDefault("delta", ""));
                            if (!delta.isEmpty() && onDelta != null) {
                                onDelta.accept(delta); // 回调增量文本
                            }
                        }
                        // 可按需处理其他事件类型，比如 response.completed 等
                    } catch (Exception ignore) {
                        // 单个分片解析失败时忽略，避免中断整体流
                    }
                }
            }
            return null;
        };

        restTemplate.execute(url, HttpMethod.POST, requestCallback, responseExtractor);
    }

    public Map createImage(String model, String prompt, Integer n, String size) throws JsonProcessingException {
        String url = "https://api.openai.com/v1/images/generations";
        Map<String, Object> map = new HashMap<>();
        map.put("model", model);
        map.put("prompt", prompt);
        map.put("n", n);
        map.put("size", size);

        HttpEntity<Map> httpEntity = new HttpEntity<>(map, null); // 这里传body 没有传header

        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        return objectMapper.readValue(exchange.getBody(), Map.class);
    }
}
